//测试
const THIS_API_MOUTH = "https://study.duyiedu.com"
const TOKEN = "token"

// 存令牌函数
function setTOKEN() {
    let headers = {}
    const token = localStorage.getItem(TOKEN)//存令牌
    if (token) {
        headers.authorization = `Bearer ${token}`
    }
}

function get(url) {
    setTOKEN()
    return fetch(THIS_API_MOUTH + url, { headers })
}
function post(url, bodyObj) {
    let headers = {
        "Content-Type": "application/json",
    }
    setTOKEN()
    return fetch(THIS_API_MOUTH + url, { headers, method: "POST", body: JSON.stringify(bodyObj) })
}

/**
 * 
 * @param {Object} userInfo 传入一个对象，格式为
 * {
        "loginId": "账号",
        "nickname": "昵称",
        "loginPwd": "密码"
    }
 */
async function zhuce(userInfo) {
    const resp = await post("/api/user/reg", userInfo)
    //下面是拿请求体,有令牌就保存 -> authorization
    const result = await resp.json()
    if (result.code === 0) {
        //把authorization保存
        const token = resp.headers.get("authorization")
        localStorage.setItem(TOKEN, token)
    }
    return result
}

/**
 * 
 * @param {Object} userInfo 传入一个对象，格式为
 * {
        "loginId": "账号",
        "loginPwd": "密码"
    }
 */
async function denglu(userInfo) {
    const resp = await fetch(THIS_API_MOUTH + "/api/user/login", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(userInfo)
        //上面是拿请求头
    })
    //下面是拿请求体
    return await resp.json()
}